﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Formatting.Compact;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ILogger = Serilog.ILogger;

namespace EFCoreDemo
{
    public class TestDBContext : DbContext
    {
        private readonly ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>builder.AddSerilog(logger));

        private static ILogger logger;

        public TestDBContext()
        {
            method();
        }


        public static void method() {
            if (logger == null) {                
                logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.File(new CompactJsonFormatter(), "Log.txt")
               .CreateLogger();
            }
        }



        public DbSet<Person> Persons { get; set; }
        public DbSet<Book> Books { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            string connStr = "server=82.157.168.172;database=TestDemo;uid=feng;pwd=123456Feng!;charset=utf8;";
            optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr))
           .EnableDetailedErrors()
           .EnableSensitiveDataLogging();
            //optionsBuilder.LogTo(Console.WriteLine);
            optionsBuilder.UseLoggerFactory(loggerFactory);

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            base.OnModelCreating(modelBuilder);
            //从当前程序集加载所有的IEntityTypeConfiguration
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
           //modelBuilder.Entity<Book>().Property(p => p.Title).HasMaxLength(200); //也可以在这里配置属性的信息
        }
    }
}
